package cn.gs.serializable.entity;

// @author gs
import cn.gs.util.stream.TokenReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class ArrayEntity implements IEntity {

    private List<IEntity> entities = new LinkedList<IEntity>();

    public ArrayEntity() {
    }

    public ArrayEntity(Collection<IEntity> entities) {
        this.entities.addAll(entities);
    }

    @Override
    public void write(EntityController ctrl, Writer w) throws IOException {
        boolean b = false;
        w.write("[");
        for (IEntity i : getEntities()) {
            if (b) {
                w.write(",");
            } else {
                b = true;
            }
            i.write(ctrl, w);
        }
        w.write("]");
    }

    @Override
    public boolean read(EntityController ctrl, TokenReader reader) throws IOException {
        String c = reader.get();
        if (!"[".equals(c.trim())) {
            reader.back();
            return false;
        }
        IEntity e;
        while ((e = ctrl.read(reader)) != null) {
            getEntities().add(e);
            c = reader.get();
            if (!",".equals(c.trim())) {
                reader.back();
                break;
            }
        }
        c = reader.get();
        if (!"]".equals(c.trim())) {
            reader.back();
            return false;
        }
        return true;
    }

    @Override
    public String toString(String prefix) {
        StringWriter w = new StringWriter();
        w.write("[\n");
        for (IEntity i : getEntities()) {
            String s = i.toString(prefix + " ");
            w.write(s);
            w.write("\n");
        }
        w.write(prefix);
        w.write("]");
        return w.toString();
    }

    @Override
    public String toString() {
        return toString("");
    }

    public List<IEntity> getEntities() {
        return entities;
    }

    public void setEntities(List<IEntity> entities) {
        this.entities = entities;
    }
}
